const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");//提取css文件

var json = require('../package.json');           //将依赖包抽

module.exports = function (options) {
    const PUBLICPATH = options.publicPath || '/';
    const dirname = options.dirname;        //当前路径
    const entry = ["@babel/polyfill",path.join(__dirname,"../src/index.js")];

    console.log('---------  webpack.base.jsx--------',options.isDev,options.publicPath)

    return {
        mode : options.isDev ? 'development' : 'production',
        entry: {
            //index: options.isDev ? entry.concat(`webpack-hot-middleware/client?path=${PUBLICPATH}__webpack_hmr`) : entry
            index:entry,
            vendor: Object.keys(json.dependencies)
        },
        output: {
            publicPath: PUBLICPATH,
            filename: options.isDev ? 'js/[name].js' : "js/[name].[hash:5].chunk.js",
            path: path.resolve(dirname, 'dist'),
            chunkFilename: options.isDev?'[name].js':"[name].[hash:5].chunk.js",
        },
        module: {
            rules: [
                {
                    test:/\.jsx?$/,
                    exclude:'/node_modules/',
                    loader: "babel-loader"
                },
                {
                    test: /\.css$/,
                    exclude:'/node_modules/',
                    use: [
                        MiniCssExtractPlugin.loader,
                        'css-loader'
                    ]
                },
                {
                    test:/\.(png|jpg|gif)$/,
                    exclude:'/node_modules/',
                    use:[{
                        loader:'url-loader',
                        options:{ // 这里的options选项参数可以定义多大的图片转换为base64
                            limit:50000, // 表示小于50kb的图片转为base64,大于50kb的是路径
                            outputPath:path.resolve(dirname, 'images') //定义输出的图片文件夹
                        }
                    }]
                },
                {
                    test: /\.(woff|woff2|eot|ttf|otf)$/,
                    exclude:'/node_modules/',
                    use:'url-loader?limit=5000' // 限制大小5kb
                },
                {
                    test: /\.s?[ac]ss$/,
                    use: options.loaders.styles
                }, 
                {
                    test: /\.(jpe?g|png|gif|svg)$/i,
                    use: options.loaders.imageAssets
                }, 
                {
                    test: /\.(woff|woff2|eot|ttf|otf)$/,
                    use: options.loaders.iconFonts
                }
             ]
        },
        resolve: {
            extensions: ['.js', '.jsx'],
        },
        
        context: dirname,
        plugins: (options.beforePlugins || []).concat([
            new webpack.DefinePlugin(options.globals),
    
            new HtmlWebpackPlugin({
                alwaysWriteToDisk: true,
                title:'马云逸的博客',
                template: path.resolve(dirname, 'src/index.tmpl.html'),
                hash: false,
                favicon: path.resolve(dirname, 'public/icon-live.png'),
                filename: 'index.html',
                inject: 'body',
                minify: {
                    collapseWhitespace: true,
                    removeComments: true,
                    removeAttributeQuotes: true
                }
            }),
            new MiniCssExtractPlugin({
                filename: options.isDev ? 'css/[name].css' : 'css/[name].[hash:8].css',
                chunkFilename: options.isDev ? '[name]-[id].css' : '[name]-[id].[hash:8].css',
            }),
            new webpack.optimize.SplitChunksPlugin({
                chunks: "async", // 必须三选一： "initial" | "all"(默认就是all) | "async"
                minSize: 3000, // 最小尺寸，默认0
                minChunks: 1, // 最小 chunk ，默认1
                maxAsyncRequests: 1, // 最大异步请求数， 默认1
                maxInitialRequests: 1, // 最大初始化请求书，默认1
                cacheGroups: { // 这里开始设置缓存的 chunks
                    priority: 0, // 缓存组优先级
                    vendor: { // key 为entry中定义的 入口名称
                        chunks: "async", // 必须三选一： "initial" | "all" | "async"(默认就是异步)
                        name: "vendor", // 要缓存的 分隔出来的 chunk 名称
                        minSize: 0,
                        minChunks: 1,
                        enforce: true,
                        maxAsyncRequests: 1, // 最大异步请求数， 默认1
                        maxInitialRequests: 1, // 最大初始化请求书，默认1
                        reuseExistingChunk: true // 可设置是否重用该chunk（查看源码没有发现默认值）
                    }
                }
            }),
            new LodashModuleReplacementPlugin
        ]),
        externals: {
            'highlight': 'hljs'
        },
        optimization: {
            splitChunks: {
                chunks: 'async',
                minSize: 30000,
                maxSize: 0,
                minChunks: 1,
                maxAsyncRequests: 5,
                maxInitialRequests: 3,
                automaticNameDelimiter: '~',
                name: true,
                cacheGroups: {
                    vendors: {
                        test: /[\\/]node_modules[\\/]/,
                        priority: -10
                    },
                    default: {
                        minChunks: 2,
                        priority: -20,
                        reuseExistingChunk: true
                    }
                }
            }
        }
    }

};
